<?php

class DefaultController extends Controller {

    protected $_model;
    protected $_arrParam;
    protected $_actionMain;
    protected $_namespace;
    protected $pages = 10;

    public function init() {
        parent::init();
        $date = date('Y-m-d'); 
        $this->_arrParam['month'] = date('d');
        $this->_arrParam['week'] = date('w', strtotime($date));       
              
        for( $i = 0; $i < $this->_arrParam['week']; $i++ ){
            $arr_date_week[] = date('Y-m-d', strtotime($date . "-$i days"));                   
        } 
        for( $i = 0; $i < $this->_arrParam['month']; $i++ ){
            $arr_date_month[] = date('Y-m-d', strtotime($date . "-$i days"));                   
        } 
        $this->_arrParam['controller'] = Yii::app()->getController()->getId();
        $this->_actionMain = $this->_arrParam['controller'] . '/index';
        $this->_namespace = $this->_arrParam['controller'];
        $ssFilter = Yii::app()->session[$this->_namespace];
        $this->_arrParam['ssFilter']['keywords'] = $ssFilter['keywords'];
        $this->_arrParam['ssFilter']['select_date'] = $ssFilter['select_date'];
        $this->_arrParam['ssFilter']['date_from'] = $ssFilter['date_from'];
        $this->_arrParam['ssFilter']['date_to'] = $ssFilter['date_to'];        
        //day
        $criteria_events_day = new CDbCriteria;
        $criteria_events_day->select = 'date(posteddate) as date, COUNT(id) as mem_count';        
        $criteria_events_day->condition = "DATEDIFF(date(posteddate),'" . date('Y-m-d') . "') >= 0"; 
        $criteria_mem_day = new CDbCriteria;
        $criteria_mem_day->select = 'date(createddate) as date, COUNT(id) as mem_count';        
        $criteria_mem_day->condition = "DATEDIFF(date(createddate),'" . date('Y-m-d') . "') >= 0";     
        $events_day = Events::model()->findAll($criteria_events_day);  
        $member_day = Member::model()->findAll($criteria_mem_day);
        $this->_arrParam['event_day'] = $events_day;
        $this->_arrParam['member_day'] = $member_day;
        //week
        $criteria_events_week = new CDbCriteria;
        $criteria_events_week->select = 'date(posteddate) as date, COUNT(id) as mem_count';        
        $criteria_events_week->condition = "DATEDIFF(date(posteddate),'" . $arr_date_week[0] . "') <= 0 AND DATEDIFF(date(posteddate),'" . $arr_date_week[$this->_arrParam['week']-1] . "') >= 0";
        $criteria_mem_week = new CDbCriteria;
        $criteria_mem_week->select = 'date(createddate) as date, COUNT(id) as mem_count';        
        $criteria_mem_week->condition = "DATEDIFF(date(createddate),'" . $arr_date_week[0] . "') <= 0 AND DATEDIFF(date(createddate),'" . $arr_date_week[$this->_arrParam['week']-1] . "') >= 0";
        $events_week = Events::model()->findAll($criteria_events_week); 
        $member_week = Member::model()->findAll($criteria_mem_week);
        $this->_arrParam['events_week'] = $events_week;
        $this->_arrParam['member_week'] = $member_week;
        //month
        $criteria_events_month = new CDbCriteria;
        $criteria_events_month->select = 'date(posteddate) as date, COUNT(id) as mem_count';        
        $criteria_events_month->condition = "DATEDIFF(date(posteddate),'" . $arr_date_month[0] . "') <= 0 AND DATEDIFF(date(posteddate),'" . $arr_date_month[$this->_arrParam['month']-1] . "') >= 0";
        $criteria_mem_month = new CDbCriteria;
        $criteria_mem_month->select = 'date(createddate) as date, COUNT(id) as mem_count';        
        $criteria_mem_month->condition = "DATEDIFF(date(createddate),'" . $arr_date_month[0] . "') <= 0 AND DATEDIFF(date(createddate),'" . $arr_date_month[$this->_arrParam['month']-1] . "') >= 0";
        $events_month = Events::model()->findAll($criteria_events_month); 
        $member_month = Member::model()->findAll($criteria_mem_month);
        $this->_arrParam['events_month'] = $events_month;
        $this->_arrParam['member_month'] = $member_month;
        // meber new
        
    }

//    protected function beforeAction($action) {
//        if (Yii::app()->user->isGuest)
//            $this->redirect(Yii::app()->createUrl('Dashboard/default/login'));
//        return $_arrParam['action'] = $action->id;
//    }

    
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('login'),
                'users' => array('?'),
            ),
            array('allow',
                'actions' => array('index', 'logout', 'config', 'addConfig', 'updateConfig', 'deleteConfig', 'writeConfig'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
        $ssFilter = $this->_arrParam['ssFilter'];
        $model = new Events;
        $criteria_events = new CDbCriteria;
        $criteria_events->select = 'date(posteddate) as date, COUNT(id) as mem_count';
        $criteria_events->group = 'date(posteddate)';
        $criteria_events->condition = "DATEDIFF(date(posteddate),'" . date('Y-m-d') . "') >= 0";
        $criteria = new CDbCriteria;
        $criteria->select = 'date(createddate) as date, COUNT(id) as mem_count';
        $criteria->group = 'date(createddate)';
        $criteria->condition = "DATEDIFF(date(createddate),'" . date('Y-m-d') . "') >= 0";        
        $criteria_em = new CDbCriteria;
        $criteria_em -> order = 'date(t.posteddate) DESC';
        if( !empty($ssFilter['keywords']) )
            {                     
                $criteria_em->addCondition(" members.email LIKE '%".$ssFilter['keywords']."%'");            
            }
        $item_event = Events::model()->findAll($criteria_events);        
        $item_member = Member::model()->findAll($criteria); 
        $count = Events::model()->with('members')->count($criteria_em);
        $pages = new CPagination( $count );           
        $pages -> pageSize = $this->pages;
        $pages -> applyLimit($criteria_em); 
        $item_em = Events::model()->with('members')->findAll($criteria_em); 
        $this->render('index', array(
            'model' => $model,  
            'item_member'=>$item_member,
            'item_event'=>$item_event,
            'item_em'=>$item_em,
            'pages' => $pages
        ));
    }

    public function actionWeek(){
        $model = new Events;
        $date = date('Y-m-d');
        $num_date_week = $this->_arrParam['week'];
        for( $i = 0; $i < $num_date_week; $i++ ){
            $arr_date[] = date('Y-m-d', strtotime($date . "-$i days"));  
            $arr_member[date('Y-m-d', strtotime($date . "-$i days"))] = 0;
            $arr_event[date('Y-m-d', strtotime($date . "-$i days"))] = 0;            
        }        
        $criteria_events = new CDbCriteria;
        $criteria_events->select = 'date(posteddate) as date, COUNT(id) as mem_count';
        $criteria_events->group = 'date(posteddate)';
        $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $arr_date[0] . "') <= 0 AND DATEDIFF(date(posteddate),'" . $arr_date[$num_date_week-1] . "') >= 0";
        $criteria = new CDbCriteria;
        $criteria->select = 'date(createddate) as date, COUNT(id) as mem_count';
        $criteria->group = 'date(createddate)';
        $criteria->condition = "DATEDIFF(date(createddate),'" . $arr_date[0] . "') <= 0 AND DATEDIFF(date(createddate),'" . $arr_date[$num_date_week-1] . "') >= 0";
        $item_event = Events::model()->findAll($criteria_events); 
        $item_member = Member::model()->findAll($criteria);         
        foreach ( $item_member as $key => $value ){           
            $arr_member[$value['date']] = $value['mem_count'];
        }
        foreach ( $item_event as $key => $value ){           
            $arr_event[$value['date']] = $value['mem_count'];
        }       
        $this->render('week', array(
            'model' => $model,            
            'item_member' => $arr_member,
            'item_event'=>$arr_event,           
            'arr_date'=>$arr_date,
            'numdays' => $num_date_week
        ));
        
    }
    
    public function actionMonth(){  
        $model = new Events;
        $date = date('Y-m-d');
        $num_date_week = $this->_arrParam['month'];
        for( $i = 0; $i < $num_date_week; $i++ ){
            $arr_date[] = date('Y-m-d', strtotime($date . "-$i days"));  
            $arr_member[date('Y-m-d', strtotime($date . "-$i days"))] = 0;
            $arr_event[date('Y-m-d', strtotime($date . "-$i days"))] = 0;            
        }         
        $criteria_events = new CDbCriteria;
        $criteria_events->select = 'date(posteddate) as date, COUNT(id) as mem_count';
        $criteria_events->group = 'date(posteddate)';
        $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $arr_date[0] . "') <= 0 AND DATEDIFF(date(posteddate),'" . $arr_date[$num_date_week-1] . "') >= 0";
        $criteria = new CDbCriteria;
        $criteria->select = 'date(createddate) as date, COUNT(id) as mem_count';
        $criteria->group = 'date(createddate)';
        $criteria->condition = "DATEDIFF(date(createddate),'" . $arr_date[0] . "') <= 0 AND DATEDIFF(date(createddate),'" . $arr_date[$num_date_week-1] . "') >= 0";
        $item_event = Events::model()->findAll($criteria_events); 
        $item_member = Member::model()->findAll($criteria); 
        foreach ( $item_member as $key => $value ){           
            $arr_member[$value['date']] = $value['mem_count'];
        }
        foreach ( $item_event as $key => $value ){           
            $arr_event[$value['date']] = $value['mem_count'];
        }       
        $this->render('month', array(
            'model' => $model,            
            'item_member' => $arr_member,
            'item_event'=>$arr_event,           
            'arr_date'=>$arr_date,
            'numdays' => $num_date_week
        ));
    }
    
    public function actionMember(){
        $model = new Events;
        $ssFilter = $this->_arrParam['ssFilter'];
        $ssFilter = array_filter($ssFilter);
        $begin_date = date('Y-m-d', strtotime('-1 month'));
        $end_date = date('Y-m-d');
        $date_from = !empty($ssFilter['date_from']) ? date_create($ssFilter['date_from']) : date_create(date('Y-m-d', strtotime('-1 month')));        
        $criteria_events = new CDbCriteria;
        $criteria_events->select = 'date(posteddate) as date, COUNT(id) as mem_count';
        $criteria_events->group = 'date(posteddate)';
        $criteria = new CDbCriteria;
        $criteria->select = 'date(createddate) as date, COUNT(id) as mem_count';
        $criteria->group = 'date(createddate)';
        if ( empty($ssFilter) == false ) {            
            if (!empty($ssFilter['date_from'])) {
                $date = $ssFilter['date_from'];
                $criteria_events->condition = " DATEDIFF(date(posteddate),'" . $date . "') >= 0";
                $criteria->condition = " DATEDIFF(date(createddate),'" . $date . "') >= 0";
            }
            if (!empty($ssFilter['date_to'])) {
                $date_to = $ssFilter['date_to'];
                $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $date_to . "') <= 0";
                $criteria->condition = "DATEDIFF(date(createddate),'" . $date_to . "') <= 0";
            }
            if (!empty($ssFilter['date_from']) && !empty($ssFilter['date_to'])) {
                $date = $ssFilter['date_from'];
                $date_to = $ssFilter['date_to'];
                $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $date . "') >= 0 AND DATEDIFF(date(posteddate),'" . $date_to . "') <= 0";
                $criteria->condition = "DATEDIFF(date(createddate),'" . $date . "') >= 0 AND DATEDIFF(date(createddate),'" . $date_to . "') <= 0";
            }
            if (empty($ssFilter['date_from']) && empty($ssFilter['date_to'])) {
                $date = date('Y-m-d', strtotime('-1 month'));            
                $end_date = date('Y-m-d');
                $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $date . "') >= 0 AND DATEDIFF(date(posteddate),'" . $end_date . "') <= 0";
                $criteria->condition = "DATEDIFF(date(createddate),'" . $date . "') >= 0 AND DATEDIFF(date(createddate),'" . $end_date . "') <= 0";                
            }
        }else{
            $date = date('Y-m-d', strtotime('-1 month'));            
            $end_date = date('Y-m-d');
            $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $date . "') >= 0 AND DATEDIFF(date(posteddate),'" . $end_date . "') <= 0";
            $criteria->condition = "DATEDIFF(date(createddate),'" . $date . "') >= 0 AND DATEDIFF(date(createddate),'" . $end_date . "') <= 0";
        }                
              
        $date_to = empty($ssFilter['date_to'])? date('Y-m-d') : $ssFilter['date_to'];
        $date = empty($ssFilter['date_from'])? date('Y-m-d', strtotime('-1 month')) : $ssFilter['date_from'];        
        $startTimeStamp = strtotime($date);
        $endTimeStamp = strtotime($date_to);
        $timeDiff = abs($endTimeStamp - $startTimeStamp);
        $numberDays = $timeDiff/86400;  // 86400 seconds in one day        
        $numberDays = intval($numberDays);        
        for($i = 0; $i <=$numberDays; $i++){
            $day = date('Y-m-d', strtotime($date_to . "-$i days"));
            $arr_event[$day] = 0;
            $arr_member[$day] = 0;
        }       
        $item_event = Events::model()->findAll($criteria_events);
        $item = Member::model()->findAll($criteria); 
        foreach ( $item_event as $key => $value ){           
            $arr_event[$value['date']] = $value['mem_count'];
        }
        foreach ( $item as $key => $value ){           
            $arr_member[$value['date']] = $value['mem_count'];
        }          
        $date_from = !empty($ssFilter['date_from']) ? date_create($ssFilter['date_from']) : date_create(date('Y-m-d', strtotime('-1 month')));
        $date_to = date_create($end_date);
        $interval = $date_from->diff($date_to);
        $num = $interval->days + 1;
        for ($i = 1; $i < $num; $i++) {
            $date1 = $item[0]['date'];
            $tomorrow = date('Y-m-d', strtotime($date1 . "+$i days"));
            $arr[$tomorrow] = 0;
        }
        if(!isset($arr))
            $arr= array();                    
        $this->render('member', array(
            'model' => $model,            
            'item' => $item,
            'item_event'=>$arr_event,
            'item_member'=>$arr_member,
            'arr' => $arr,
            'numdays' => $num
        ));
    }

    public function actionLogin() {
        $this->layout = '//layouts/defaultLogin';
        $model = new LoginForm;

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            if ($model->validate() && $model->login()) {
                $this->redirect(array('/Dashboard/default/index'));
            }
        }

        $this->render('login', array(
            'model' => $model
        ));
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionConfig() {
        $model = new Configs;
        $dataProvider = new CActiveDataProvider('Configs', array(
            'sort' => array(
                'defaultOrder' => 'id ASC',
            ),
            'pagination' => array(
                'pageSize' => 10,
                'pageVar' => 'page',
            ),
                )
        );

        $this->render('config', array(
            'dataProvider' => $dataProvider,
            'model' => $model
        ));
    }

    public function actionAddConfig() {
        $model = new Configs;
        if (isset($_POST['Configs'])) {
            $model->attributes = $_POST['Configs'];
            $model->posteddate = $model->updatedate = date('Y-m-d H:i:s');
            if ($model->save()) {
                $this->redirect(array('/Dashboard/default/config'));
            }
        }
    }

    public function actionUpdateConfig($id) {
        $model = Configs::model()->findByPk($id);

        if (isset($_POST['Configs'])) {
            $model->attributes = $_POST['Configs'];
            $model->updatedate = date('Y-m-d H:i:s');
            if ($model->save()) {
                $this->redirect(array('/Dashboard/default/config'));
            }
        }

        $this->render('updateConfig', array(
            'model' => $model
        ));
    }

    public function actionDeleteConfig($id) {
        $model = Configs::model()->findByPk($id)->delete();

        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    public function actionWriteConfig() {
        $model = Configs::model()->findAll();

        $fp = fopen(CONFIG_MAIN_FILE, "w");
        fwrite($fp, "<?php" . PHP_EOL);
        fclose($fp);
        foreach ($model as $x => $data) {
            if ($x >= 0) {
                file_put_contents(CONFIG_MAIN_FILE, "define('$data->key', '" . str_replace("'", "\'", $data->value) . "');" . PHP_EOL, FILE_APPEND);
            } else {
                file_put_contents(CONFIG_MAIN_FILE, "define('$data->key', '" . str_replace("'", "\'", $data->value) . "');" . PHP_EOL);
            }
        }
        /*
          foreach ($model as $data) {
          fwrite($fp, mb_convert_encoding ("define('$data->key', '".str_replace("'", "\'", $data->value)."');".PHP_EOL, 'UTF-8'));
          }
          fclose($fp);
         */
        $this->redirect(array('/Dashboard/default/config'));
    }
    public function actionFilters() {            
            $ssFilter = Yii::app()->session;                                          
            if( isset( $_GET['type'] ) && isset( $_GET['key'] ) ){                                
                if( $_GET['type'] == 'search' && $_GET['key'] == 1 ){                    
                    if( !empty( $_POST['date_from'] ) )
                        $arr['date_from'] = $_POST['date_from'];
                    else
                        $arr['date_from'] = ''; 
                    if( !empty( $_POST['date_to'] ) )
                        $arr['date_to'] = $_POST['date_to'];
                    else
                        $arr['date_to'] = ''; 
                    if( !empty( $_POST['select_date'] ) )
                        $arr['select_date'] = $_POST['select_date'];
                    else
                        $arr['select_date'] = '';                         
                    if( !empty( $_POST['keywords'] ) ){
                        $arr['keywords'] = $_POST['keywords'];                        
                    }else
                        $arr['keywords'] = '';                     
                    if( !empty( $_POST['date_to'] ) && !empty( $_POST['date_to'] ) ){
                        if( strtotime($_POST['date_from']) > strtotime($_POST['date_to']) ){
                            $arr['date_from'] = '';
                            $arr['date_to'] = ''; 
                        }else{
                        $arr['date_from'] = $_POST['date_from'];
                        $arr['date_to'] = $_POST['date_to'];
                        }
                    }                     
                }
                else
                {
                        $arr['date_from'] = '';
                        $arr['date_to'] = '';
                        $arr['select_date'] = ''; 
                        $arr['keywords'] = '';                        
                }
                $ssFilter[$this->_namespace] = $arr;
            }                              
            $this->redirect( isset($_GET['mail'])? array('/Dashboard/default/index'): array('/Dashboard/default/member') );                                                         
        }
}